package com.atguigu.spzx.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.spzx.model.entity.user.AuthContextUtil;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.entity.user.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 前台拦截器
 * @author Mahone
 */
@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        StringBuffer requestUrl = request.getRequestURL();
        System.out.println("前台LoginAuthInterceptor拦截器：" + requestUrl);
        // 从网关过滤器重新赋值的请求头获取userInfo
        String userInfoJson = request.getHeader("userInfoJson");
        if (!StringUtils.isEmpty(userInfoJson)){
            // userInfoJson不为空，则将其json字符串转化为userInfo对象
            UserInfo userInfo = JSON.parseObject(userInfoJson, UserInfo.class);
            if (null != userInfo){
                // 转换成功 存入本地线程
                AuthContextUtil.setUserInfo(userInfo);
            }
        }
        System.out.println("前置拦截器");
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清空本地线程

        System.out.println("拦截器工作完成后");
    }
}
